<template>
  <a-modal
    v-model:open="visible"
    title="收银结算"
    width="800px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="cashier-settlement-modal">
      <!-- 账单信息 -->
      <div class="bill-info">
        <div class="info-row">
          <div class="info-item">
            <span class="label">总金额:</span>
            <span class="value">¥{{ bill?.totalAmount.toFixed(2) }}元</span>
          </div>
          <div class="info-item">
            <span class="label">顾客姓名:</span>
            <span class="value">{{ bill?.ownerName }}</span>
          </div>
          <div class="info-item">
            <span class="label">押金:</span>
            <span class="value">¥{{ customerDeposit.toFixed(2) }}元</span>
          </div>
        </div>
      </div>

      <!-- 打折方式 -->
      <div class="discount-section">
        <h4>打折方式</h4>
        <a-radio-group
          v-model:value="discountMethod"
          @change="handleDiscountChange"
        >
          <a-radio value="membership">会员卡折扣</a-radio>
          <a-radio value="whole">整单折扣</a-radio>
          <a-radio value="none">不使用打折</a-radio>
        </a-radio-group>

        <div v-if="discountMethod === 'membership'" class="membership-discount">
          <a-radio-group v-model:value="selectedMembershipCard">
            <a-radio value="002">002 金卡(7折)</a-radio>
            <a-radio value="003">003 银卡(8折)</a-radio>
          </a-radio-group>
        </div>

        <div v-if="discountMethod === 'whole'" class="whole-discount">
          <a-input-number
            v-model:value="wholeDiscountAmount"
            :min="0"
            :max="bill?.totalAmount || 0"
            :precision="2"
            placeholder="输入折扣金额"
            style="width: 200px"
          />
        </div>

        <div class="manual-price">
          <span class="label">抹零:</span>
          <a-input-number
            v-model:value="roundingAmount"
            :min="0"
            :max="10"
            :precision="2"
            placeholder="抹零金额"
            style="width: 120px"
          />
        </div>
      </div>

      <!-- 最终应付金额 -->
      <div class="final-amount">
        <div class="amount-display">
          <span class="label">最终应付金额:</span>
          <span class="value">¥{{ finalAmount.toFixed(2) }}</span>
        </div>
        <div class="amount-breakdown">
          <div class="breakdown-item">
            <span>原价: ¥{{ bill?.totalAmount.toFixed(2) }}</span>
            <span>共优惠: ¥{{ totalDiscount.toFixed(2) }}</span>
            <span>获得积分: {{ earnedPoints }}</span>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-methods">
        <h4>选择支付方式</h4>
        <div class="payment-grid">
          <div class="payment-item">
            <a-checkbox v-model:checked="paymentMethods.alipay">
              支付宝
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.alipay"
              :min="0"
              :max="finalAmount"
              :precision="2"
              placeholder="金额"
              style="width: 120px"
            />
          </div>
          <div class="payment-item">
            <a-checkbox v-model:checked="paymentMethods.wechat">
              微信
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.wechat"
              :min="0"
              :max="finalAmount"
              :precision="2"
              placeholder="金额"
              style="width: 120px"
            />
          </div>
          <div class="payment-item">
            <a-checkbox v-model:checked="paymentMethods.cash">
              现金
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.cash"
              :min="0"
              :max="finalAmount"
              :precision="2"
              placeholder="金额"
              style="width: 120px"
            />
          </div>
          <div class="payment-item">
            <a-checkbox v-model:checked="paymentMethods.card">
              银行卡
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.card"
              :min="0"
              :max="finalAmount"
              :precision="2"
              placeholder="金额"
              style="width: 120px"
            />
          </div>
          <div class="payment-item">
            <a-checkbox v-model:checked="paymentMethods.deposit">
              押金
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.deposit"
              :min="0"
              :max="customerDeposit"
              :precision="2"
              placeholder="金额"
              style="width: 120px"
            />
          </div>
        </div>
      </div>

      <!-- 会员卡支付 -->
      <div class="membership-payment">
        <h4>会员卡支付</h4>
        <div class="membership-info">
          <a-checkbox v-model:checked="useMembershipCard">
            002 金卡
          </a-checkbox>
          <div class="card-info">
            <span>余额: 1,000.00</span>
            <span>赠额: 0.00</span>
          </div>
          <div class="balance-payment">
            <span class="label">余额支付:</span>
            <a-input-number
              v-model:value="membershipBalancePayment"
              :min="0"
              :max="1000"
              :precision="2"
              placeholder="余额支付金额"
              style="width: 150px"
            />
          </div>
          <div class="gift-payment">
            <span class="label">赠额支付:</span>
            <a-input-number
              v-model:value="membershipGiftPayment"
              :min="0"
              :max="0"
              :precision="2"
              placeholder="赠额支付金额"
              style="width: 150px"
            />
          </div>
        </div>
      </div>

      <!-- 备注 -->
      <div class="remarks-section">
        <h4>备注</h4>
        <a-textarea
          v-model:value="remarks"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </div>

      <!-- 底部选项 -->
      <div class="bottom-options">
        <a-checkbox v-model:checked="autoPrint"> 结算自动完成打印 </a-checkbox>
        <div class="payment-total">
          <span class="label">支付合计:</span>
          <span class="value">¥{{ totalPaymentAmount.toFixed(2) }}元</span>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

// 接口定义
interface BillItem {
  id: string;
  name: string;
  specification: string;
  unit: string;
  quantity: number;
  unitPrice: number;
  discountedPrice: number;
  total: number;
  salesPerson: string;
  servicePerson: string;
  category: string;
  date: string;
}

interface Bill {
  id: string;
  petName: string;
  petId: string;
  ownerName: string;
  ownerPhone: string;
  createTime: string;
  status: 'unsettled' | 'onAccount' | 'settled' | 'refund';
  totalAmount: number;
  items: BillItem[];
}

interface Props {
  visible: boolean;
  bill: Bill | null;
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const discountMethod = ref<'membership' | 'whole' | 'none'>('none');
const selectedMembershipCard = ref('002');
const wholeDiscountAmount = ref(0);
const roundingAmount = ref(0);
const customerDeposit = ref(50); // 模拟顾客押金

// 模拟会员卡数据
const membershipCards = ref([
  {
    id: '002',
    name: '金卡',
    discountRate: 0.7,
    balance: 1000,
    giftAmount: 0,
  },
  {
    id: '003',
    name: '银卡',
    discountRate: 0.8,
    balance: 500,
    giftAmount: 50,
  },
  {
    id: '004',
    name: '普通卡',
    discountRate: 0.9,
    balance: 200,
    giftAmount: 0,
  },
]);

const paymentMethods = ref({
  alipay: false,
  wechat: false,
  cash: false,
  card: false,
  deposit: false,
});

const paymentAmounts = ref({
  alipay: 0,
  wechat: 0,
  cash: 0,
  card: 0,
  deposit: 0,
});

const useMembershipCard = ref(false);
const membershipBalancePayment = ref(0);
const membershipGiftPayment = ref(0);
const remarks = ref('');
const autoPrint = ref(false);

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const finalAmount = computed(() => {
  let amount = props.bill?.totalAmount || 0;

  // 应用折扣
  if (discountMethod.value === 'membership') {
    const discountRate = selectedMembershipCard.value === '002' ? 0.7 : 0.8;
    amount = amount * discountRate;
  } else if (discountMethod.value === 'whole') {
    amount = amount - wholeDiscountAmount.value;
  }

  // 应用抹零
  amount = amount - roundingAmount.value;

  return Math.max(0, amount);
});

const totalDiscount = computed(() => {
  return (props.bill?.totalAmount || 0) - finalAmount.value;
});

const earnedPoints = computed(() => {
  return Math.floor(finalAmount.value);
});

const totalPaymentAmount = computed(() => {
  let total = 0;

  if (paymentMethods.value.alipay) total += paymentAmounts.value.alipay;
  if (paymentMethods.value.wechat) total += paymentAmounts.value.wechat;
  if (paymentMethods.value.cash) total += paymentAmounts.value.cash;
  if (paymentMethods.value.card) total += paymentAmounts.value.card;
  if (paymentMethods.value.deposit) total += paymentAmounts.value.deposit;
  if (useMembershipCard.value) {
    total += membershipBalancePayment.value;
    total += membershipGiftPayment.value;
  }

  return total;
});

// 方法
const handleDiscountChange = () => {
  // 重置相关金额
  if (discountMethod.value === 'membership') {
    wholeDiscountAmount.value = 0;
  } else if (discountMethod.value === 'whole') {
    selectedMembershipCard.value = '002';
  } else {
    wholeDiscountAmount.value = 0;
    selectedMembershipCard.value = '002';
  }
};

const handleOk = () => {
  // 验证支付金额
  if (Math.abs(totalPaymentAmount.value - finalAmount.value) > 0.01) {
    message.warning('支付金额与应付金额不匹配');
    return;
  }

  // 验证至少选择了一种支付方式
  const hasPaymentMethod =
    Object.values(paymentMethods.value).some((v) => v) ||
    useMembershipCard.value;
  if (!hasPaymentMethod) {
    message.warning('请至少选择一种支付方式');
    return;
  }

  message.success('收银结算成功');
  emit('success');
  emit('update:visible', false);
  resetForm();
};

const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  discountMethod.value = 'none';
  selectedMembershipCard.value = '002';
  wholeDiscountAmount.value = 0;
  roundingAmount.value = 0;

  paymentMethods.value = {
    alipay: false,
    wechat: false,
    cash: false,
    card: false,
    deposit: false,
  };

  paymentAmounts.value = {
    alipay: 0,
    wechat: 0,
    cash: 0,
    card: 0,
    deposit: 0,
  };

  useMembershipCard.value = false;
  membershipBalancePayment.value = 0;
  membershipGiftPayment.value = 0;
  remarks.value = '';
  autoPrint.value = false;
};

// 监听最终金额变化，自动设置支付金额
watch(finalAmount, (newAmount) => {
  if (newAmount > 0) {
    // 默认设置为现金支付
    paymentMethods.value.cash = true;
    paymentAmounts.value.cash = newAmount;
  }
});

// 监听模态框打开，重置表单
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      resetForm();
    }
  },
);
</script>

<style scoped>
.cashier-settlement-modal {
  padding: 16px 0;
}

.bill-info,
.discount-section,
.final-amount,
.payment-methods,
.membership-payment,
.remarks-section {
  margin-bottom: 24px;
}

.bill-info h4,
.discount-section h4,
.final-amount h4,
.payment-methods h4,
.membership-payment h4,
.remarks-section h4 {
  margin: 0 0 16px;
  font-size: 16px;
  color: #333;
}

.info-row {
  display: flex;
  gap: 24px;
}

.info-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.info-item .label {
  font-size: 14px;
  color: #666;
}

.info-item .value {
  font-weight: 500;
  color: #333;
}

.membership-discount,
.whole-discount {
  padding: 12px;
  margin: 16px 0;
  background: #f8f9fa;
  border-radius: 4px;
}

.manual-price {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 16px;
}

.manual-price .label {
  font-size: 14px;
  color: #666;
}

.amount-display {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 8px;
}

.amount-display .label {
  font-size: 16px;
  color: #333;
}

.amount-display .value {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
}

.amount-breakdown {
  font-size: 14px;
  color: #666;
}

.breakdown-item {
  display: flex;
  gap: 16px;
}

.payment-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.payment-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.membership-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.card-info {
  display: flex;
  gap: 16px;
  margin: 12px 0;
  font-size: 14px;
  color: #666;
}

.balance-payment,
.gift-payment {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 8px;
}

.balance-payment .label,
.gift-payment .label {
  min-width: 80px;
  font-size: 14px;
  color: #666;
}

.bottom-options {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.payment-total {
  display: flex;
  gap: 8px;
  align-items: center;
}

.payment-total .label {
  font-size: 16px;
  color: #333;
}

.payment-total .value {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}
</style>
